/**
 * @Author:Geln Yang
 * @Created:2008-8-3 $ Revision: 1.0 $ $ Author: Geln Yang $ $ Date: 2008-8-3 $
 */
package com.hgy.commonsale.service.impl;

import java.util.Date;
import java.util.List;
import org.geln.web.hibernate.BaseHibernateService;
import org.geln.web.status.Status;
import com.hgy.commonsale.service.IUserManager;
import com.hgy.commonsale.user.domain.User;

/**
 * @Author:Geln Yang
 * @Created:2008-8-3
 */
public class UserManagerImpl extends BaseHibernateService implements IUserManager {

	public User getUserByAccount(String account) {
		String queryString = "from User where account = ? ";
		List<User> list = getHibernateTemplate().find(queryString, new String[] { account });
		if (list != null && list.size() == 1) {
			return (User) list.get(0);
		}
		return null;
	}

	public User getUserById(String id) {
		List<User> list = this.findNameQuery("getUserById", new String[] { id }, null);
		if (list != null && list.size() == 1) {
			return list.get(0);
		}
		return null;
	}

	public Status saveOrUpdate(User user) {
		if (user == null)
			return Status.FAILED_FOR_NULL;
		if (user.getId() == null || user.getId().trim().length() == 0) {
			return save(user);
		} else {
			return update(user);
		}

	}

	protected Status update(User user) {
		String userId = user.getId();
		getHibernateTemplate().evict(user);
		User dbUser = getUserById(userId);
		if (dbUser == null) {
			return Status.FAILED;
		} else {
			dbUser.copyUpdateInfo(user);
			dbUser.setModifiedTime(new Date());
			getHibernateTemplate().update(dbUser);
			return Status.SUCCESS;
		}
	}

	protected Status save(User user) {
		if (exists(user.getAccount()))
			return Status.FAILED;
		user.setModifiedTime(new Date());
		getHibernateTemplate().save(user);
		return Status.SUCCESS;
	}

	public boolean exists(String loginName) {
		User user = getUserByAccount(loginName);
		if (user != null)
			return true;
		return false;
	}

}
